package com.example.demoreptile.article;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;


/**
 * 小说url接口实现类
 *
 * @author zhangjunfa
 * @date 2023/8/9 8:50
 */
public class IChapterInterImpl implements IChapterInter {

    private String prefixUrl;

    public IChapterInterImpl(String prefixUrl) {
        this.prefixUrl = prefixUrl;
    }

    protected String crawl(String url) throws Exception {
        //采用HttpClient技术
        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build();
             CloseableHttpResponse httpResponse = httpClient.execute(new HttpGet(url))) {
            String result = EntityUtils.toString(httpResponse.getEntity(), "utf-8");
            return result;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    @Override
    public List<Chapter> getChapter(String url) {
        try {
            String result = crawl(url);
            Document doc = Jsoup.parse(result);
            Elements as = doc.select(".listmain dd a");
            List<Chapter> chapters = new ArrayList<>();
            for (Element a : as) {
                Chapter chapter = new Chapter();
                chapter.setTitle(a.text());
                chapter.setUrl(prefixUrl + a.attr("href"));
                chapters.add(chapter);
            }
            return chapters;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取文章的详细内容
     *
     * @param url 文章链接
     * @return
     */
    @Override
    public String getContent(String url) {
        try {
            String result = crawl(url);
            Document doc = Jsoup.parse(result);
            //获取小说的正文
            String content = doc.select("#content").html();

            //处理特殊数据
            content = content.replace("一本读|ＷｗんＷ．『yb→du→．co", "");
            content = content.replace("<br>", "");
            content = content.replace("&nbsp;", "");
            content = content.replaceAll("<.*?>", "");
            return content;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


}